package com.example.saiweisi.service.impl.userService;

import com.example.saiweisi.controller.request.RechargeRequest;
import com.example.saiweisi.exception.ServiceException;
import com.example.saiweisi.mapper.userMapper.VipCardMapper;
import com.example.saiweisi.model.VipCardKind;
import com.example.saiweisi.service.interf.IVipCardService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class VipCardService implements IVipCardService {
    @Resource
    VipCardMapper vipCardMapper;
    @Override
    public void buyVipCard(Integer userId, Integer vipKindId) {
        if(vipCardMapper.getVipCardByUserId(userId)==0){
            //遍历数据库，将最大的 num加一 赋值给新用户，来达到生成唯一标识符的目的
            int s=1;
            List<Integer> cardNumlist=vipCardMapper.getCardNum();
            for (Integer a:cardNumlist
            ) {
                if(a>s){
                    s=a;
                }
            }
            int vipCardNum=++s;
            double vipKindPrice = vipCardMapper.getvipKindBalance(vipKindId);
            vipCardMapper.buyVipCard(userId,vipKindId,vipCardNum,vipKindPrice);
        }else {
            if(vipCardMapper.getVipKindZhekoulv(vipKindId)
                    <vipCardMapper.getVipKindZhekoulv(vipCardMapper.getVipKindIdByUserId(userId))){
                double vipCardBalance=vipCardMapper.getvipCardBalanceByUserId(userId);
                vipCardBalance+=vipCardMapper.getvipKindBalance(vipKindId);
                vipCardMapper.updateVipCard(userId,vipCardBalance,vipKindId);
            }else {

                throw new ServiceException("您已有一个等级更高的会员卡了");
            }
      }
    }

    @Override
    public VipCardKind getVipCard(Integer userId) {
        VipCardKind vipCard =new VipCardKind();
        try {
            vipCard = vipCardMapper.getVipCard(userId);
        }catch (Exception e){
            throw new ServiceException("没有超级会员哦");
        }
        return vipCard;

    }

    @Override
    public void recharge(RechargeRequest rechargeRequest) {
        vipCardMapper.recharge(rechargeRequest);
    }
}
